<template>
  <div class="table-box">
    <!-- 主表格 -->
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格顶部按钮区 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增公司 </el-button>
        <el-button type="primary" :icon="Download" @click="downloadFile">导出客户数据</el-button>
      </template>

      <!-- 表格展开行内容 -->
      <template #expand="scope">
        {{ scope.row }}
      </template>

      <!-- 表格操作列 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openInfoDrawer('查看', scope.row)"> 查看 </el-button>
        <el-button v-auth="'edit'" type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)"> 编辑 </el-button>
        <el-button v-auth="'edit'" type="primary" link :icon="Refresh" @click="openResetPass(scope.row)"> 重置密码 </el-button>
        <el-button v-auth="'delete'" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>

    <!-- 抽屉组件 -->
    <UserDrawer ref="drawerRef" />
    <InfoDrawer ref="infoDrawerRef" />

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPassDialogVisible" title="重置联系人密码" width="30%">
      <el-form label-width="100px">
        <el-form-item label="选择联系人">
          <el-select v-model="selectedContactId" placeholder="请选择要重置密码的联系人" style="width: 100%" clearable>
            <el-option
              v-for="contact in currentContacts"
              :key="contact.id || contact.phone"
              :label="`${contact.name}(${contact.position}) - ${contact.phone}`"
              :value="contact.id || contact.phone"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPassDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmResetPass">重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import { Customer, ColumnForm } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import UserDrawer from "@/views/home/components/UserDrawer.vue";
import InfoDrawer from "@/views/home/components/InfoDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Refresh, Download } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/modules/user";
import { getCustomerList, deleteCustomer, updateCustomer, addCustomer, resetCustomerPassWord } from "@/api/modules/user";
import { getTableColums } from "@/api/modules/tableMange";
// 存储相关
const userStore = useUserStore();

// 组件引用
const proTable = ref<ProTableInstance>();
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const infoDrawerRef = ref<InstanceType<typeof InfoDrawer> | null>(null);

// 表格状态
const columns = reactive<ColumnProps<Customer.DynamicCustomerInfo>[]>([]);
const drawRowColumn = reactive<ColumnForm<Customer.DynamicCustomerInfo>[]>([]);
const initParam = reactive({ type: userStore.userInfo.permissions });

// 重置密码对话框状态
const resetPassDialogVisible = ref(false);
const selectedContactId = ref("");
const currentContacts = ref<Customer.ContactPerson[]>([]);
const currentEnterpriseName = ref("");
const currentEnterpriseId = ref("");

// 常量定义
const RENDER_TYPES = {
  IMAGE: "img",
  STRING_ARRAY: "strArr",
  OBJECT_ARRAY: "objArr"
};

const OPERATION_TYPES = {
  ADD: "新增",
  EDIT: "编辑",
  VIEW: "查看"
};

// 生命周期钩子
onMounted(() => {
  initializeTableColumns();
});

// 方法定义

/**
 * 初始化表格列配置
 */
const initializeTableColumns = async () => {
  try {
    const arr = await getTableColums({
      permission: userStore.userInfo.permissions
    });

    processColumns(arr);
    addSelectionColumn();
    addConfigColumn();
  } catch (error) {
    console.error("初始化表格列失败:", error);
    ElMessage.error("初始化表格列失败");
  }
};

/**
 * 处理列配置数据
 */
const processColumns = (columnsData: any[]) => {
  columnsData.forEach(column => {
    const baseColumn: ColumnForm = {
      prop: column.key,
      label: column.label,
      isShow: column.isShow,
      renderType: column.renderType,
      formConfig: typeof column.formConfig == "string" && column.formConfig ? JSON.parse(column.formConfig) : column.formConfig,
      required: column.required,
      category: column.category,
      placeholderTemplate: column.placeholderTemplate,
      unit: column.unit
    };

    const fullColumn = {
      ...baseColumn,
      sortable: column.sortable,
      displayField: column.displayField,
      width: column.width
    };

    columns.push(fullColumn);
    drawRowColumn.push(baseColumn);
  });

  configureColumnRenderers();
};

/**
 * 配置列渲染器
 */
const configureColumnRenderers = () => {
  columns.forEach(column => {
    if (!column.renderType) return;

    switch (column.renderType) {
      case RENDER_TYPES.IMAGE:
        column.render = renderImage;
        break;
      case RENDER_TYPES.STRING_ARRAY:
        column.render = renderStringArray;
        break;
      case RENDER_TYPES.OBJECT_ARRAY:
        if (column.displayField) {
          column.render = renderObjectArray(column);
        }
        break;
    }
  });
};

/**
 * 图片渲染器
 */
const renderImage = (scope: any) =>
  scope.row[scope.column.property] ? (
    <el-image
      src={scope.row[scope.column.property]}
      style="width: 60px; height: 60px; border-radius: 4px;"
      preview-src-list={[scope.row[scope.column.property]]}
      preview-teleported={true}
    />
  ) : (
    <el-avatar shape="square" size={60}>
      img
    </el-avatar>
  );

/**
 * 字符串数组渲染器
 */
const renderStringArray = (scope: any) => {
  const arrData = scope.row[scope.column.property];
  const arr =
    typeof arrData === "string" && arrData ? arrData.split(",").filter((item: string) => item.trim() !== "") : arrData || [];

  return arr.length > 0 ? (
    <>
      {arr.map((tag: string) => (
        <el-tag type="success" size="small" class="truncate" style={{ minWidth: "100px", margin: "0 5px" }}>
          {tag}
        </el-tag>
      ))}
    </>
  ) : (
    <span>暂无</span>
  );
};

/**
 * 对象数组渲染器
 */
const renderObjectArray = (column: ColumnProps<Customer.DynamicCustomerInfo>) => (scope: any) => {
  const displayFields =
    typeof column.displayField === "string" && column.displayField
      ? column.displayField.split(",").filter((item: string) => item.trim() !== "")
      : (column.displayField as string[]) || [];

  const arrData = scope.row[column.prop!] || [];
  const newArr = arrData.map((item: any) => displayFields.map(key => item[key]).join("-"));

  return newArr.length > 0 ? (
    <>
      {newArr.map((tag: string) => (
        <el-tag type="success" size="small" class="truncate" style={{ minWidth: "100px", margin: "0 5px" }}>
          {tag}
        </el-tag>
      ))}
    </>
  ) : (
    <span>暂无</span>
  );
};

/**
 * 添加选择列
 */
const addSelectionColumn = () => {
  columns.unshift({ type: "selection", fixed: "left", width: 70 });
};

/**
 * 添加搜索列
 */
const addConfigColumn = () => {
  columns.push({
    prop: "keyName",
    label: "关键词",
    isShow: false,
    isSetting: false,
    search: { el: "input", tooltip: "请输入关键词" }
  });
  columns.push({
    prop: "operation",
    label: "操作",
    isShow: true,
    isSetting: false,
    width: 330
  });
};

/**
 * 数据回调处理
 */
const dataCallback = (data: any) => ({
  list: data.list,
  total: data.total
});

/**
 * 获取表格数据
 */
const getTableList = (params: any) => {
  const newParams = { ...params };
  delete newParams.createTime;
  return getCustomerList(newParams);
};

/**
 * 表格排序处理
 */
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log("排序变化:", { newIndex, oldIndex });
  ElMessage.success("修改列表排序成功");
};

/**
 * 删除公司账号
 */
const deleteAccount = async (params: Customer.CustomerInfo) => {
  await useHandleData(deleteCustomer, { id: [params.id] }, `删除【${params.enterpriseName}】公司`);

  if (proTable.value) {
    const index = proTable.value.selectedListIds.indexOf(params.id);
    if (index > -1) {
      proTable.value.selectedListIds.splice(index, 1);
      proTable.value.selectedList.splice(
        proTable.value.selectedList.findIndex(c => c.ids === params.id),
        1
      );
    }
    proTable.value.getTableList();
  }
};

/**
 * 打开抽屉（新增/编辑）
 */
const openDrawer = (title: string, row: Partial<Customer.CustomerInfo> = {}) => {
  const params = {
    title,
    row: { ...row },
    columns: drawRowColumn,
    api: title === OPERATION_TYPES.ADD ? addCustomer : title === OPERATION_TYPES.EDIT ? updateCustomer : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

/**
 * 打开查看抽屉
 */
const openInfoDrawer = (title: string, row: Partial<Customer.CustomerInfo> = {}) => {
  const params = {
    title,
    row: { ...row },
    columns: drawRowColumn
  };
  infoDrawerRef.value?.acceptParams(params);
};

/**
 * 打开重置密码对话框
 */
const openResetPass = (row: Customer.CustomerInfo) => {
  currentContacts.value = row.contacts || [];
  currentEnterpriseName.value = row.enterpriseName;
  currentEnterpriseId.value = row.id;
  selectedContactId.value = "";
  resetPassDialogVisible.value = true;
};

/**
 * 确认重置密码
 */
const confirmResetPass = async () => {
  if (!selectedContactId.value) {
    ElMessage.warning("请选择要重置密码的联系人");
    return;
  }

  const selectedContact = currentContacts.value.find(
    contact => contact.id === selectedContactId.value || contact.phone === selectedContactId.value
  );

  if (!selectedContact) {
    ElMessage.error("未找到选中的联系人");
    return;
  }

  await useHandleData(
    resetCustomerPassWord,
    {
      contactId: selectedContact.id || selectedContact.phone
    },
    `重置【${currentEnterpriseName.value}】公司的联系人【${selectedContact.name}】密码为123456`
  );

  resetPassDialogVisible.value = false;
  proTable.value?.getTableList();
};

// 导出函数
const downloadFile = async () => {
  let obj = {
    ...proTable.value?.searchParam,
    pageNum: 1,
    pageSize: proTable.value?.pageable.total as number
  };
  let { list } = await getCustomerList(obj);
  const tableData = list || [];

  const exportColumns = columns
    .filter(
      (col): col is { prop: string; label: string; displayField: string } =>
        !!col.prop && !!col.displayField && !!col.label && col.prop !== "logo"
    )
    .map(col => ({ prop: col.prop, label: col.label, displayField: col.displayField }));
  console.log("导出参数：", exportColumns);
  console.log(tableData);
  ElMessageBox.confirm("确认导出客户数据？", "温馨提示", { type: "warning" }).then(() =>
    useDownload(tableData, "客户数据表", exportColumns)
  );
};
</script>

<style scoped>
.table-box {
  width: 100%;
  height: 100%;
}
</style>
